<?php

declare(strict_types=1);

namespace App\Request\Web;

use App\Model\Article;
use Hyperf\Context\Context;
use Hyperf\Contract\ValidatorInterface;
use Hyperf\Validation\Request\FormRequest;
use Hyperf\Validation\Rule;

class PublishArticleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'strategy' => ['required', Rule::in(['immediately', 'scheduled', 'self', 'password'])],
            'published_at' => ['required_if:strategy,scheduled', 'date', 'after_or_equal:now'],
            'password' => ['required_if:strategy,password', 'string', 'max:50'],
        ];
    }

    public function withValidator(ValidatorInterface $validator)
    {
        $validator->after(function ($validator) {
            $id = $this->route('id');

            $exists = Article::where('id', $id)
                ->where('user_id', Context::get('uid'))
                ->where('status', 'review')
                ->exists();

            if (!$exists) {
                $validator->errors()->add('id', '文章未找到或不处于审核状态');
            }
        });
    }
}
